﻿using Kimd.Common;
using Kimd.Machine;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using WorkStation.UI;

namespace WorkStation
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                //设置应用程序处理异常方式：ThreadException处理
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                //处理UI线程异常
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                //处理非UI线程异常
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                #region 防重开
                bool createNew = false;
                Mutex mutex = new Mutex(true, "WorkStation", out createNew);
                var currentProcess = Process.GetCurrentProcess();
                if (!createNew)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("软件重复打开，请确认是否打开新软件？");
                    sb.Append("[Yes] 打开新软件，旧软件自动关闭");
                    sb.Append("[No] 新软件直接退出！");
                    if (MessageBox.Show(sb.ToString(), "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    {
                        return;
                    }
                    Process[] process = Process.GetProcessesByName("WorkStation");
                    while (process.Length > 1)
                    {
                        foreach (var item in process)
                        {
                            if (item.Id != currentProcess.Id)
                            {
                                item.Kill();
                            }
                        }
                        Thread.Sleep(100);
                        process = Process.GetProcessesByName("WorkStation");
                    }
                }
                #endregion

                #region 启动窗体
                FormStartUp formStartUp = new FormStartUp(Properties.Settings.Default.ConfigName);
                if (formStartUp.ShowDialog() == DialogResult.OK)
                {
                    Application.Run(new FormMain(formStartUp.startUpInfo));
                }
                #endregion
            }
            catch (Exception ex)
            {
                string str = GetExceptionMsg(ex, string.Empty);
                MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        static string GetExceptionMsg(Exception ex, string backStr)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("****************************异常文本****************************");
            sb.AppendLine("【出现时间】：" + DateTime.Now.ToString("yyyyMMdd HHmmss_ffff"));
            if (ex != null)
            {
                sb.AppendLine("【异常类型】：" + ex.GetType().Name);
                sb.AppendLine("【异常信息】：" + ex.Message);
                sb.AppendLine("【堆栈调用】：" + ex.StackTrace);
                sb.AppendLine(ex.ToString());
            }
            else
            {
                sb.AppendLine("【未处理异常】：" + backStr);
            }
            sb.AppendLine("***************************************************************");
            MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, sb.ToString(), "Main", 0, "系统", ex));
            return sb.ToString();
        }
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.Exception, e.ToString());
            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}
